import pandas as pd
import json
import os
from typing import Dict, List

def load_win_rate_data(csv_path: str) -> pd.DataFrame:
    """加载OPGG胜率CSV文件并进行数据清洗
    
    Args:
        csv_path: CSV文件路径
        
    Returns:
        处理后的DataFrame，包含排名、英雄名称、胜率、选取率、禁用率和被克制信息
    """
    # 加载CSV文件
    df = pd.read_csv(csv_path)
    
    # 数据清洗
    # 1. 将百分比字符串转换为浮点数
    percentage_columns = ['Win_Rate', 'Pick_Rate', 'Ban_Rate']
    for col in percentage_columns:
        df[col] = df[col].str.rstrip('%').astype(float) / 100
    
    # 2. 将Countered_By列中的字符串转换为英雄列表
    df['Countered_By'] = df['Countered_By'].str.split(', ')
    
    return df

def load_ddragon_mapping(json_dir: str) -> Dict[str, str]:
    """
    加载Data Dragon的JSON文件，构建一个中文名->英文名的映射字典。
    例如：{"黑暗之女": "Annie", "狂战士": "Olaf", ...}
    
    Args:
        json_dir: 包含英雄JSON文件的目录路径
        
    Returns:
        中文名到英文名的映射字典
    """
    mapping = {}
    
    # 遍历目录下的所有JSON文件
    for filename in os.listdir(json_dir):
        if filename.endswith('.json'):
            file_path = os.path.join(json_dir, filename)
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    
                    # 提取英雄数据
                    # 假设英雄数据在data['data'][英雄ID]路径下
                    for champ_id, champ_data in data['data'].items():
                        chinese_name = champ_data['name']
                        english_name = champ_id
                        
                        # 特别处理猴子，将MonkeyKing映射为Wukong
                        if english_name == 'MonkeyKing':
                            english_name = 'Wukong'
                        
                        mapping[chinese_name] = english_name
            except Exception as e:
                print(f"处理文件 {filename} 时出错: {e}")
    
    return mapping

def get_project_win_rate_df():
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    # 构建指向data目录的相对路径
    project_root = os.path.dirname(current_dir)
    data_path = os.path.join(project_root, 'data', 'opgg_top_tier_list.csv')
    return load_win_rate_data(data_path)

def get_project_ddragon_mapping():
    current_dir = os.path.dirname(os.path.abspath(__file__))
    # 构建指向data目录的相对路径
    project_root = os.path.dirname(current_dir)
    data_path = os.path.join(project_root, 'data', 'champion')
    return load_ddragon_mapping(data_path)

def create_alias_map(ddragon_mapping: Dict[str, str]) -> Dict[str, str]:
    """
    基于官方映射，创建一个扩展的别名映射字典。
    这是"硬编码"少量常见别名的地方。
    """
    alias_map = {}
    # 1. 首先，官方中文名->英文名的映射是基础
    alias_map.update(ddragon_mapping)

    # 2. 手动添加一些最常用的别名
    common_aliases = {
        "剑魔": "Aatrox",
        "诺手": "Darius",
        "德莱厄斯": "Darius", 
        "盖伦": "Garen",
        "鳄鱼": "Renekton",
        "刀妹": "Irelia",
        "石头人": "Malphite",
        "吸血鬼": "Vladimir",
        "猴子": "Wukong",
        "悟空": "Wukong",
        "盲僧": "LeeSin",
        "李青": "LeeSin",
        "亚索": "Yasuo",
        "永恩": "Yone",
        "EZ": "Ezreal",
        "探险家": "Ezreal",
        "VN": "Vayne",
        "暗夜猎手": "Vayne",
        "小法": "Veigar",
        "维迦": "Veigar",
        "火男": "Brand",
        "布兰德": "Brand",
        "日女": "Leona",
        "蕾欧娜": "Leona",
        "风女": "Janna",
        "迦娜": "Janna",
        "锤石": "Thresh",
        "机器人": "Blitzcrank",
        "蒸汽": "Blitzcrank",
        "布里茨": "Blitzcrank",
        "拉克丝": "Lux",
        "光辉": "Lux",
        "金克丝": "Jinx",
        "女警": "Caitlyn",
        "凯特琳": "Caitlyn",
        "蔚": "Vi",
        "皮城执法官": "Vi",
        "螳螂": "Khazix",
        "卡兹克": "Khazix",
        "狮子狗": "Rengar",
        "雷恩加尔": "Rengar",
        "龙女": "Shyvana",
        "希瓦娜": "Shyvana",
        "男枪": "Graves",
        "格雷福斯": "Graves",
        "卡牌": "TwistedFate",
        "扭曲树精": "Maokai",
        "茂凯": "Maokai",
        "妖姬": "Leblanc",
        "乐芙兰": "Leblanc",
        "扇子妈": "Karma",
        "卡尔玛": "Karma",
        "大虫子": "Chogath",
        "科加斯": "Chogath",
        "火女": "Annie",
        "安妮": "Annie",
        "天使": "Kayle",
        "凯尔": "Kayle",
        "莫甘娜": "Morgana",
        "卡特": "Katarina",
        "卡特琳娜": "Katarina",
        "塞恩": "Sion",
        "老司机": "Sion",
        "酒桶": "Gragas",
        "塔姆": "TahmKench",
        "蛤蟆": "TahmKench",
        "千珏": "Kindred",
        "老鼠": "Twitch",
        "图奇": "Twitch",
        "轮子妈": "Sivir",
        "希维尔": "Sivir",
        "炼金": "Singed",
        "辛吉德": "Singed",
        "大发明家": "Heimerdinger",
        "黑默丁格": "Heimerdinger",
        "炸弹人": "Ziggs",
        "吉格斯": "Ziggs",
        "奥拉夫": "Olaf",
        "狂战士": "Olaf",
        "武器大师": "Jax",
        "贾克斯": "Jax",
        "赵信": "XinZhao",
        "德邦总管": "XinZhao",
        "狗头": "Nasus",
        "内瑟斯": "Nasus",
        "蝎子": "Skarner",
        "斯卡纳": "Skarner",
        "猪妹": "Sejuani",
        "瑟庄妮": "Sejuani",
        "波比": "Poppy",
        "波比": "Poppy",
        "努努": "Nunu",
        "雪人骑士": "Nunu",
        "小炮": "Tristana",
        "崔丝塔娜": "Tristana",
        "大嘴": "KogMaw",
        "克格莫": "KogMaw",
        "蚂蚱": "Malzahar",
        "马尔扎哈": "Malzahar",
        "冰女": "Lissandra",
        "丽桑卓": "Lissandra",
        "冰鸟": "Anivia",
        "艾尼维亚": "Anivia",
        "小法": "Veigar",
        "维迦": "Veigar",
        "兰博": "Rumble",
        "蒸汽机器人": "Blitzcrank",
        "发条": "Orianna",
        "奥莉安娜": "Orianna",
        "婕拉": "Zyra",
        "蜘蛛": "Elise",
        "伊莉丝": "Elise",
        "EZ": "Ezreal",
        "探险家": "Ezreal",
        "VN": "Vayne",
        "暗夜猎手": "Vayne",
        "Uzi": "Vayne",
        "男刀": "Talon",
        "泰隆": "Talon",
        "女坦": "Leona",
        "日女": "Leona",
        "扇子妈": "Karma",
        "卡尔玛": "Karma",
        "风女": "Janna",
        "迦娜": "Janna",
        "琴女": "Sona",
        "娑娜": "Sona",
        "娜美": "Nami"
    }
    alias_map.update(common_aliases)

    return alias_map